import O1HD from "../gameEngine";

const {ccclass, property} = cc._decorator;

enum SCROLLTYPE{
    HORIZONTAL,
    VERTICAL,
}

@ccclass
export default class slider extends cc.Component {

    @property({type:cc.Enum(SCROLLTYPE),tooltip:"滚动方向"})
    scrollType:SCROLLTYPE = SCROLLTYPE.HORIZONTAL;

    @property({type:cc.Node,tooltip:"itemContent节点"})
    itemContent:cc.Node = null;

    @property({type:cc.Node,tooltip:"item节点"})
    item:cc.Node = null;

    @property({tooltip:"显示的节点数量"})
    showItemCount:number = 3;

    @property({tooltip:"每个节点间隔距离"})
    itemInterval:number = 0;

    @property({type:cc.SpriteFrame,tooltip:"被选中的节点的图片"})
    selectSpf:cc.SpriteFrame = null;

    @property({type:cc.SpriteFrame,tooltip:"未选中的节点的图片"})
    noSelectSpf:cc.SpriteFrame = null;

    @property({type:cc.SpriteFrame,tooltip:"未解锁图片"})
    lockSpf:cc.SpriteFrame = null;

    curMinIndex:number = 0;
    curMaxIndex:number = 0;

    minIndex:number = 0;
    maxIndex:number = Number.MAX_VALUE;

    _curSelectNode:cc.Node = null;

    start(){
        this.addTouchEvent();
    }

    loadSlider(startIndex:number = 0,startScroll:number = 0,minIndex:number = 0,maxIndex:number = Number.MAX_VALUE,){
        this.minIndex = minIndex;
        this.maxIndex = maxIndex;
        let createCount:number = this.showItemCount * 3;
        this.curMinIndex = startIndex;
        this.curMaxIndex = startIndex + createCount;
        for(let i =0; i<createCount; i++){
            let node:cc.Node = cc.instantiate(this.item);
            node.active = true;
            this.itemContent.addChild(node);
            let mPos:number = this.getPosByIndex(i + startIndex);
            let pos:cc.Vec2 = cc.v2();
            switch(this.scrollType){
                case SCROLLTYPE.HORIZONTAL:{
                    pos = cc.v2(mPos,0);
                    break;
                }
                case SCROLLTYPE.VERTICAL:{
                    pos = cc.v2(0,mPos);
                    break;
                }
            }
            node.setPosition(pos);
            this.refrenshOneNodeData();
        }
        this.scrollToIndex(startScroll,0);
    }

    addTouchEvent(){
        this.node.on('touchstart',this.onTouchStart,this);
        this.node.on("touchmove",this.onTouchMove,this);
        this.node.on('touchend',this.onTouchEnd,this);
        this.node.on('touchcancel',this.onTouchCancel,this);
    }

    removeTouchEvent(){
        this.node.off('touchstart',this.onTouchStart,this);
        this.node.off("touchmove",this.onTouchMove,this);
        this.node.off('touchend',this.onTouchEnd,this);
        this.node.off('touchcancel',this.onTouchCancel,this);
    }

    scrollToIndex(index:number,time:number){
        let vec2:cc.Vec2 = cc.v2(0,0);
        let pos:number = this.getPosByIndex(index);
        switch(this.scrollType){
            case SCROLLTYPE.HORIZONTAL:{
                    vec2 = cc.v2(-pos,0);
                break;
            }
            case SCROLLTYPE.VERTICAL:{
                    vec2 = cc.v2(0,-pos);
                break;
            }
        }
        //@ts-ignore
        cc.tween(this.itemContent).to(time,{position:vec2}).call(()=>{
            this.refrenshSpf();
        }).start();
    }

    getPosByIndex(index:number){
        let mPos:number = index * (this.itemInterval + this.item.width);
        switch(this.scrollType){
            case SCROLLTYPE.HORIZONTAL:{
                mPos = index * (this.itemInterval + this.item.width);
                break;
            }
            case SCROLLTYPE.VERTICAL:{
                mPos = index * (this.itemInterval + this.item.height);
                break;
            }
        }
        return mPos;
    }

    getIndexByPos(pos:cc.Vec2){
        switch(this.scrollType){
            case SCROLLTYPE.HORIZONTAL:{
                return Math.floor(pos.x / (this.itemInterval + this.item.width));
                break;
            }
            case SCROLLTYPE.VERTICAL:{
                return Math.floor(pos.y / (this.itemInterval + this.item.height));
                break;
            }
        }
    }

    refrenshItemPos(detal:number){
        if(detal < 0){
            this.itemContent.children.concat().forEach((n:cc.Node)=>{
                switch(this.scrollType){
                    case SCROLLTYPE.HORIZONTAL:{
                        let nPos:cc.Vec2 = n.convertToWorldSpaceAR(cc.v2());
                        let cPos:cc.Vec2 = this.node.convertToWorldSpaceAR(cc.v2());
                        let distance:number = nPos.sub(cPos).mag();
                        if(distance > O1HD.Canvas().width / 2 + this.item.width * 2 && nPos.x < cPos.x){
                            let posX:number = this.getPosByIndex(this.curMaxIndex);
                            n.setPosition(cc.v2(posX,n.y));
                            this.curMaxIndex ++;
                            this.curMinIndex ++;
                        }
                        break;
                    }
                    case SCROLLTYPE.VERTICAL:{
                        if(n.y < this.node.height  + this.item.height * 1.5){
    
                        }
                        break;
                    }
                }
            });
        }else{
            this.itemContent.children.concat().forEach((n:cc.Node)=>{
                switch(this.scrollType){
                    case SCROLLTYPE.HORIZONTAL:{
                        let nPos:cc.Vec2 = n.convertToWorldSpaceAR(cc.v2());
                        let cPos:cc.Vec2 = this.node.convertToWorldSpaceAR(cc.v2());
                        let distance:number = nPos.sub(cPos).mag();
                        if(distance > O1HD.Canvas().width / 2 + this.item.width * 2 && nPos.x > cPos.x){
                            let posX:number = this.getPosByIndex(this.curMinIndex);
                            n.setPosition(cc.v2(posX,n.y));
                            this.curMaxIndex --;
                            this.curMinIndex --;
                        }
                        break;
                    }
                    case SCROLLTYPE.VERTICAL:{
                        if(n.y > this.node.height  + this.item.height * 1.5){
    
                        }
                        break;
                    }
                }
            });
        }
    }

    onTouchStart(e:cc.Event.EventTouch){
        cc.Tween.stopAllByTarget(this.itemContent);
    }

    onTouchMove(e:cc.Event.EventTouch){
        let detal:cc.Vec2 = e.getDelta();
        let d : number = 0;
        switch(this.scrollType){
            case SCROLLTYPE.HORIZONTAL:{
                // 横向滚动
                let xDetal:number = detal.x;
                let minX:number = this.getPosByIndex(this.minIndex);
                let maxX:number = this.getPosByIndex(this.maxIndex);
                if(this.itemContent.x + xDetal > minX ){
                    xDetal = minX - this.itemContent.x;
                }else if(this.itemContent.x + xDetal < -maxX){
                    xDetal = this.itemContent.x + maxX;
                }
                this.itemContent.x += xDetal;    
                d = xDetal;
                break;
            }
            case SCROLLTYPE.VERTICAL:{
                // 竖向滚动
                let yDetal:number = detal.y;
                if(this.itemContent.x + yDetal > 0){
                    yDetal = 0 - this.itemContent.x;
                }
                this.itemContent.y += yDetal;
                d = yDetal;
                break;
            }
        }
        this.refrenshItemPos(d);
        this.refrenshSpf();
    }

    onTouchEnd(e:cc.Event.EventTouch){
        cc.Tween.stopAllByTarget(this.itemContent);
        let minDistanceIndex:number = this.getMinDistanceItemIndex();
        let mNode:cc.Node = this.itemContent.children[minDistanceIndex];
        this._curSelectNode = mNode;
        let cIndex:number = this.getIndexByPos(this._curSelectNode.getPosition());
        if(cIndex <= O1HD.getManagers().peopleArcheryManager.getData().infinityLevel){
        this._curSelectNode.getComponent(cc.Sprite).spriteFrame = this.selectSpf;
        }
        let pos:cc.Vec2 = this.node.convertToNodeSpaceAR(mNode.convertToWorldSpaceAR(cc.v2()));
        // console.log(minDistanceIndex,"怎么个事",this.curMinIndex,this.getIndexByPos(mNode.getPosition()),mNode);
        // mNode.color = cc.Color.RED;
        //@ts-ignore
        cc.tween(this.itemContent).by(0.2,{position:pos.negate()}).call(()=>{
        }).start();
        // this.refrenshSpf();
    }

    onTouchCancel(e:cc.Event.EventTouch){
        this.onTouchEnd(e);
    }

    refrenshOneNodeData(){
        this.itemContent.children.forEach((n:cc.Node)=>{
            let index:number = this.getIndexByPos(n.getPosition());
            let label:cc.Label = n.getChildByName("label").getComponent(cc.Label);
            label.string = (index + 1).toString();
        });
    }

    refrenshScale(){
        this.itemContent.children.forEach((n:cc.Node)=>{
            let index:number = this.getIndexByPos(n.getPosition());
            if(index < this.minIndex || index > this.maxIndex){
                n.scale = 0;
            }else{
                let nPos:cc.Vec2 = n.convertToWorldSpaceAR(cc.v2());
                let cPos:cc.Vec2 = this.node.convertToWorldSpaceAR(cc.v2());
                let distance:number = nPos.sub(cPos).mag();
                let scale = (O1HD.Canvas().width / 2 - distance) / (O1HD.Canvas().width / 2) * 0.2 + 0.8; 
                n.scale =  scale;
            }

            let aNode:cc.Node = n.getChildByName("zhujiemianui__9");
            if(index == this.maxIndex){
                aNode.active = false;
            }else{
                aNode.active = true;
            }

        });
    }

    refrenshSpf(){
        this.itemContent.children.forEach((n:cc.Node)=>{
            let index = this.getIndexByPos(n.getPosition());
            if(index <= O1HD.getManagers().peopleArcheryManager.getData().infinityLevel){
                n.getComponent(cc.Sprite).spriteFrame = this.noSelectSpf;
            }else{
                n.getComponent(cc.Sprite).spriteFrame = this.lockSpf;
            }
            // console.log(index,O1HD.getManagers().peopleArcheryManager.getData().infinityLevel);
        });
        let minDistanceIndex = this.getMinDistanceItemIndex();
        let node:cc.Node = this.itemContent.children[minDistanceIndex];
        this._curSelectNode = node;
        let cIndex:number = this.getIndexByPos(this._curSelectNode.getPosition());
        if(cIndex <= O1HD.getManagers().peopleArcheryManager.getData().infinityLevel){
            this._curSelectNode.getComponent(cc.Sprite).spriteFrame = this.selectSpf;
        }
    }

    getMinDistanceItemIndex(){
        let minDistance:number = 10000000;
        let minDistanceIndex:number = 0;
        this.itemContent.children.forEach((n:cc.Node,index:number)=>{
            let nPos:cc.Vec2 = n.convertToWorldSpaceAR(cc.v2());
            let cPos:cc.Vec2 = this.node.convertToWorldSpaceAR(cc.v2());
            let distance:number = nPos.sub(cPos).mag();
            if(distance < minDistance){
                minDistance = distance;
                minDistanceIndex = index;
            }
        });
        return minDistanceIndex;
    }

    getCurSelectIndex(){
        return this.getIndexByPos(this._curSelectNode.getPosition());
    }

    update(dt: number){
        this.refrenshOneNodeData();
        this.refrenshScale();
    }
    
}
